package com.itrui.jiami;

import org.apache.tomcat.jni.FileInfo;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {
    public static void main(String[] args) throws IOException, InterruptedException {
        //思路
        //在本机 的8888端口监听, 等待连接
        ServerSocket serverSocket = new ServerSocket(8888);
        System.out.println("服务器端，监听8888端口，等待连接");

        //当没有客户端连接8888端口时，程序会 阻塞, 等待连接
        //如果有客户端连接，则会返回Socket对象，程序继续
        Socket socket = serverSocket.accept();

        receiveFile(socket,"D:\\RuiProject\\Server");

    }

    protected static void receiveFile(Socket socket, String mFilePath) throws InterruptedException {
        File dirs = new File(mFilePath);
        if (!dirs.exists()) {
            dirs.mkdirs();
        }

        DataInputStream din = null;
        int fileNum = 0;
        long totalSize = 0;
        FileInfo[] fileinfos = null;

        try {
            din = new DataInputStream(new BufferedInputStream(socket.getInputStream()));

            fileNum = din.readInt();
            fileinfos = new FileInfo[fileNum];
            for (int i = 0; i < fileNum; i++) {
                fileinfos[i] = new FileInfo();
                fileinfos[i].fname = din.readUTF();
                fileinfos[i].size = din.readLong();
            }
            totalSize = din.readLong();
        } catch (IOException e) {
            e.printStackTrace();
            //Log.d(TAG,"readInt Exception");
            System.out.println("readInt Exception");
            System.exit(0);
        }
        System.out.println("文件个数："+fileNum);
        System.out.println("文件总大小: "+totalSize);
        for (FileInfo fileinfo : fileinfos) {
            int i = 1;
            System.out.println("第" + i +"个文件名："+fileinfo.fname);
            System.out.println("第" + i +"个文件大小："+fileinfo.size);
            i++;
        }

        int leftLen = 0; // 写满文件后缓存区中剩余的字节长度。
        int bufferedLen = 0; // 当前缓冲区中的字节数
        int writeLen = 0; // 每次向文件中写入的字节数
        long writeLens = 0; // 当前已经向单个文件中写入的字节总数
        long totalWriteLens = 0; // 写入的所有字节数

        byte buf[] = new byte[8192];

        for (int i = 0; i < fileNum; i++) {
            System.out.println("正在接收第"+ (i + 1) +"个文件...");
            writeLens = 0;
            try {
                /*System.out.println(mFilePath + "\\"+ fileinfos[i].fname);
                System.out.println(mFilePath + fileinfos[i].fname);*/
                FileOutputStream fout = new FileOutputStream(mFilePath + "\\"+ fileinfos[i].fname);

                while (true) {
                    if (leftLen > 0) {
                        bufferedLen = leftLen;
                    } else {
                        bufferedLen = din.read(buf);
                    }
                    if (bufferedLen == -1) return;

                    //System.out.println("readlen：" + bufferedLen);
                    // 如果已写入文件的字节数加上缓存区中的字节数已大于文件的大小，只写入缓存区的部分内容。
                    if (writeLens + bufferedLen >= fileinfos[i].size) {
                        leftLen = (int) (writeLens + bufferedLen - fileinfos[i].size);
                        writeLen = bufferedLen - leftLen;
                        fout.write(buf, 0, writeLen); // 写入部分
                        totalWriteLens += writeLen;
                        move(buf, writeLen, leftLen);
                        break;
                    } else {
                        fout.write(buf, 0, bufferedLen); // 全部写入
                        writeLens += bufferedLen;
                        totalWriteLens += bufferedLen;
                        if (totalWriteLens >= totalSize) {
                            //mListener.report(GroupChatActivity.FAIL, null);
                            return;
                        }
                        leftLen = 0;
                    }
                    //mListener.report(GroupChatActivity.PROGRESS,
                    //(int) (totalWriteLens * 100 / totalSize));
                } // end while
                fout.close();

            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                //Log.d(TAG,"receive file Exception");
                System.out.println("readInt Exception");
            }

        } // end for
        //mListener.report(GroupChatActivity.FAIL, null);
    }

    // An highlighted block
    /**
     *
     * @param buf 读取大小
     * @param writeLen 已经写入到文件中的
     * @param leftLen 内存中剩余的字节长度
     */
    public static void move( byte buf[] ,int writeLen, int leftLen){
        for (int i = 0; i < leftLen; i++) {
            if(buf[writeLen+i] != 0){
                buf[i] = buf[writeLen+i];
            }
        }
    }

}
